package com.app.service.impl;

import com.app.common.Result;
import com.app.mapper.ClassificationSubclassMapper;
import com.app.mapper.GroupBuyingCategoryMapper;
import com.app.model.ClassificationSubclass;
import com.app.model.GroupBuyingCategory;
import com.app.service.CustomerServiceService;
import com.app.service.IClassificationSubclassService;
import com.app.service.IGroupBuyingCategoryService;
import com.app.vo.PageVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 团购分类表 服务实现类
 * </p>
 *
 * @author shaokuiling
 * @since 2024-09-24
 */
@Service
public class GroupBuyingCategoryServiceImpl extends ServiceImpl<GroupBuyingCategoryMapper, GroupBuyingCategory> implements IGroupBuyingCategoryService {
    @Autowired
    private GroupBuyingCategoryMapper groupBuyingCategoryMapper;
    @Autowired
    private ClassificationSubclassMapper classificationSubclassMapper;
    @Autowired
    private IClassificationSubclassService classificationSubclassService;

    /**
     * 团购分类表新增
     *
     * @param groupBuyingCategory
     * @return
     */
    @Override
    public Result addAndUpdate(GroupBuyingCategory groupBuyingCategory) {
        if (groupBuyingCategory.getBusinessId() == null || groupBuyingCategory.getBusinessId() <= 0) {
            return Result.error(400, "关联的商家Id不不能为空，请选择关联的商家");
        }
        if (groupBuyingCategory.getId() == null) {//新增
            groupBuyingCategory.setStatus(1);
            groupBuyingCategory.setCreateTime(LocalDateTime.now());
            if (groupBuyingCategory.getSort() == null) {
                groupBuyingCategory.setSort(0);
            }
            groupBuyingCategoryMapper.insert(groupBuyingCategory);
            return Result.success("操作成功");
        } else if (groupBuyingCategory.getId() >= 0) {//update
            groupBuyingCategory.setStatus(null);
            groupBuyingCategory.setUpdateTime(LocalDateTime.now());
            groupBuyingCategoryMapper.updateById(groupBuyingCategory);
            return Result.success("操作成功");
        }
        return Result.error(400, "非法参数，不予操作");
    }

    /**
     * 管理后台————根据活动Id查询分类列表
     *
     * @param businessId
     * @param page
     * @param limit
     * @return
     */
    @Override
    public Result getListByActivityId(Integer businessId, Integer page, Integer limit) {
        Page p = new Page(page, limit);
        QueryWrapper<GroupBuyingCategory> qw = new QueryWrapper<GroupBuyingCategory>();
        qw.eq("business_id", businessId);
        qw.eq("status", 1);
        qw.orderByDesc("sort").orderByAsc("create_time");
        Page selectPage = groupBuyingCategoryMapper.selectPage(p, qw);

        List<GroupBuyingCategory> records = selectPage.getRecords();
        if (records != null && records.size() > 0) {
            List<Integer> collect = records.stream().map(c -> {
                return c.getId();
            }).collect(Collectors.toList());

            List<ClassificationSubclass> classificationSubclasses = classificationSubclassMapper.selectList(new QueryWrapper<ClassificationSubclass>()
                    .in("category_id",collect).eq("status",1));
            for (GroupBuyingCategory groupBuyingCategory : records) {
                List<ClassificationSubclass> filteredSubclasses = classificationSubclasses.stream()
                        .filter(subclass -> subclass.getCategoryId().equals(groupBuyingCategory.getId()))
                        .collect(Collectors.toList());
                // 你可以在这里对 filteredSubclasses 做进一步处理
                // 例如，将其设置回 groupBuyingCategory 对象中
                groupBuyingCategory.setChild(filteredSubclasses);
            }
        }
        PageVo pageVo = new PageVo();
        pageVo.setCount(selectPage.getTotal());
        pageVo.setList(selectPage.getRecords());
        return Result.success(pageVo);
    }

    /**
     * 管理后台————删除团购
     *
     * @param cid  分类表Id
     * @param type 1子表仍有关联数据不予删除 2强制删除关联的子表数据
     * @return
     */
    @Override
    public Result deleteIdWithType(Integer cid, Integer type) {
        //校验cid
        if (cid == null || cid <= 0) {
            return Result.error(400, "参数错误，不予操作");
        }
        //校验type
        if (type == null || (type != 1 && type != 2)) {
            type = 1;
        }

        //删除的逻辑
        List<ClassificationSubclass> classificationSubclasses = classificationSubclassMapper.selectList(new QueryWrapper<ClassificationSubclass>().eq("category_id", cid).eq("status", 1));
        if (type == 2) {//强制删除关联表数据
            List<ClassificationSubclass> collect = classificationSubclasses.stream().map(c -> {
                ClassificationSubclass classificationSubclass = new ClassificationSubclass();
                classificationSubclass.setId(c.getId());
                classificationSubclass.setStatus(2);
                classificationSubclass.setUpdateTime(LocalDateTime.now());
                return classificationSubclass;
            }).collect(Collectors.toList());
            classificationSubclassService.updateBatchById(collect);
        }else {
            if (classificationSubclasses != null && classificationSubclasses.size() > 0) {
                return Result.error(400, "请先删除子类关联的数据，或您选择强制删除");
            }
        }
        GroupBuyingCategory groupBuyingCategory = new GroupBuyingCategory();
        groupBuyingCategory.setId(cid);
        groupBuyingCategory.setStatus(2);
        groupBuyingCategory.setUpdateTime(LocalDateTime.now());
        groupBuyingCategoryMapper.updateById(groupBuyingCategory);
        return Result.success("删除成功");


    }

    /**
     * 管理后台————根据分类Id查分类的详情
     * @param cid
     * @return
     */
    @Override
    public Result getCategoryDetail(Integer cid) {
        if(cid==null || cid<=0){
            return  Result.error(400,"参数错误");
        }
        GroupBuyingCategory groupBuyingCategory = groupBuyingCategoryMapper.selectById(cid);
        List<ClassificationSubclass> classificationSubclasses = classificationSubclassMapper.selectList(new QueryWrapper<ClassificationSubclass>()
                .eq("category_id", cid)
                .eq("status", 1)
                .orderByDesc("sort").orderByAsc("create_time"));
        groupBuyingCategory.setClassificationSubclasses(classificationSubclasses);
        return Result.success(groupBuyingCategory);
    }
}
